<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索 -->
        <!-- 顶部提示 -->

        <el-row>
          <el-col class="top_title">
            <span>说明：目前支持学科和关键字条件筛选</span>
            <el-button
              type="success"
              size="small"
              icon="el-icon-edit"
              @click="$router.push('new')"
              >新增试题</el-button
            >
          </el-col>
        </el-row>
        <!-- 搜索 -->
        <el-form :model="form" label-width="80px">
          <el-row>
            <!-- 学科 -->
            <el-col :span="6">
              <el-form-item label="学科">
                <el-select
                  style="width: 100%"
                  v-model="form.subjectID"
                  placeholder="请选择"
                  @change="onSubjectChange"
                >
                  <el-option
                    v-for="item in subjects"
                    :key="item.id"
                    :label="item.subjectName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 目录 -->
            <el-col :span="6">
              <el-form-item label="二级目录">
                <el-select
                  style="width: 100%"
                  v-model="form.catalogID"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in directory"
                    :key="item.id"
                    :label="item.directoryName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 标签 -->
            <el-col :span="6">
              <el-form-item label="标签">
                <el-select
                  style="width: 100%"
                  v-model="form.tags"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in tagList"
                    :key="item.id"
                    :label="item.tagName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 关键字 -->
            <el-col :span="6">
              <el-form-item label="关键字">
                <el-input
                  v-model="form.keyword"
                  placeholder="请根据题干搜索"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 试题类型 -->
            <el-col :span="6">
              <el-form-item label="试题类型">
                <el-select
                  style="width: 100%"
                  v-model="form.questionType"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in questionType"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 难度 -->
            <el-col :span="6">
              <el-form-item label="难度">
                <el-select
                  class="filter-item"
                  style="width: 100%"
                  v-model="form.difficulty"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in difficulty"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 方向 -->
            <el-col :span="6">
              <el-form-item label="方向">
                <el-select
                  style="width: 100%"
                  v-model="form.direction"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in direction"
                    :key="item.value"
                    :label="item"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 录入人 -->
            <el-col :span="6">
              <el-form-item label="录入人">
                <el-select
                  style="width: 100%"
                  v-model="form.creatorID"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, i) in userList"
                    :key="i"
                    :label="item.username"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 题目备注 -->
            <el-col :span="6">
              <el-form-item label="题目备注">
                <el-input v-model="form.remarks"></el-input>
              </el-form-item>
            </el-col>
            <!-- 企业简称 -->
            <el-col :span="6">
              <el-form-item label="企业简称">
                <el-input v-model="form.shortName"></el-input>
              </el-form-item>
            </el-col>
            <!-- 城市 -->
            <el-col :span="6">
              <el-form-item label="城市" width="120px">
                <MyCity v-model="provAndCity" />
              </el-form-item>
            </el-col>

            <el-col :span="6" style="text-align: right">
              <el-button @click="clear" size="small">清除</el-button>
              <el-button size="small" type="primary" @click="search">
                搜索</el-button
              >
            </el-col>
          </el-row>
        </el-form>
        <!-- 数据记录 -->
        <el-alert
          v-if="cResultTip"
          :title="cResultTip"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>
        <!-- end -->
        <!-- 数据列表 -->
        <el-table
          :data="questions"
          fit
          highlight-current-row
          style="width: 100%"
          border
        >
          <el-table-column align="center" label="试题编号" width="120px">
            <template slot-scope="scope">
              <span>{{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="学科">
            <template slot-scope="scope">
              <span>{{ scope.row.subject }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="目录">
            <template slot-scope="scope">
              <span>{{ scope.row.catalog }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="题型">
            <template slot-scope="scope">
              <span>{{ formquestionType(scope.row.questionType) }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="题干" width="150px">
            <template slot-scope="scope">
              <span v-html="scope.row.question"></span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="录入时间">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | dateFormat }} </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="难度">
            <template slot-scope="scope">
              <span>{{ formdifficulty(scope.row.difficulty) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="录入人">
            <template slot-scope="scope">
              <span>{{ scope.row.creator }}</span>
            </template>
          </el-table-column>
          <!-- 操作按钮 -->
          <el-table-column
            align="center"
            label="操作"
            width="280"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <!-- 预览 -->
              <el-button
                @click="showPreview(scope.row)"
                type="primary"
                icon="el-icon-view"
                plain
                circle
              ></el-button>
              <!-- 修改-》跳转到试题录入 -->
              <el-button
                type="success"
                @click="toEdit(scope.row)"
                icon="el-icon-edit"
                plain
                circle
              ></el-button>
              <!-- 删除 -->
              <el-button
                circle
                plain
                type="danger"
                icon="el-icon-delete"
                v-if="scope.row.status != 'deleted'"
                @click="Delete(scope.row.id)"
              ></el-button>
              <!-- 精选 -->
              <el-button
                @click="choiceAdd(scope.row)"
                plain
                size="small"
                type="warning"
                icon="el-icon-check"
                circle
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- end -->
        <!-- 分页 -->
        <!-- 分页功能 -->
        <div class="pagination" v-show="total">
          <div class="pages">
            <el-pagination
              background
              @size-change="changeSize"
              @current-change="changePage"
              :current-page="Number(form.page)"
              :total="Number(total)"
              :page-size="Number(form.pagesize)"
              :page-sizes="[2, 5, 30, 50]"
              layout=" prev, pager, next, sizes,jumper"
            ></el-pagination>
          </div>
        </div>
        <!-- end -->
      </el-card>
    </div>
    <!-- 引入封装的预览弹出层组件 -->
    <Preview
      ref="pr"
      :show-dialog.sync="showDialog"
      :question-detail.sync="questionDetail"
    />
  </div>
</template>

<script>

// 学科列表数据
import { list } from '@/api/hmmm/subjects'
// 引入用户列表
import { list as user } from '@/api/base/users'
// 标签列表
import { list as tags } from '@/api/hmmm/tags'
// 目录接口
import { list as directory } from '@/api/hmmm/directorys'
// 状态
import { status, direction, difficulty, questionType } from '@/api/hmmm/constants'
// 城市
import MyCity from './companys/citys.vue'
// 引入预览弹出层组件
import Preview from '@/module-hmmm/components/questions-preview.vue'
import { list as getques, choiceAdd, remove } from '@/api/hmmm/questions'
export default {
  name: 'QuestionsList',
  // 注册弹层组件
  components: {
    Preview, MyCity
  },

  data () {
    return {
      // 传递给详情页用于获取详情页数据
      questionDetail: {},
      showDialog: false,
      questions: [],
      // 学科列表数据
      subjects: [],
      // 目录
      catalog: [],
      // 录入人列表
      userList: [],
      // 目录
      directory: [],
      // 标签
      tagList: [],
      total: 0,
      // 城市
      provAndCity: {
        province: null,
        city: null
      },

      // 查询表单中的参数
      form: {
        // 企业简称
        shortName: null,
        tags: null, // 标签
        catalogID: null, // 二级目录
        subjectID: null, // 学科
        questionType: null, // 试题类型
        direction: null, // 方向
        // 关键字
        keyword: null,
        // 录入人
        creatorID: null,
        // 题目备注
        remarks: null,
        // 页数
        page: 1,
        pagesize: 5,

        difficulty: null // 难度

      }
    }
  },
  // 创建完毕,做一次查询
  created () {
    // 题库列表
    this.getQuestion()
    // 获取学科
    this.getSubject()
    // 获取录入人
    this.getCreator()
  },
  computed: {
    status () {
      return status
    },
    cResultTip () {
      return `共 ${this.total} 条记录`
    },
    direction () {
      return direction
    },
    difficulty () {
      return difficulty
    },
    questionType () {
      return questionType
    }
  },

  methods: {
    // 搜索关键字
    search () {
      this.form.page = 1
      this.getQuestion()
    },
    // 清除表单数据
    clear () {
      for (const key in this.form) {
        if (key === 'page' || key === 'pagesize') {
          continue
        }
        this.form[key] = null
      }
      this.provAndCity = {
        province: '',
        city: ''
      }
      this.tagList = this.directory = []
    },
    // 获取学科
    async getSubject () {
      const { data } = await list()
      // console.log('学科信息', data)
      this.subjects = data.items
      // this.catalog = data.items
    },
    //  获取录入人
    async getCreator () {
      try {
        const { data: res } = await user()
        // console.log('录入人', res)
        this.userList = res.list
      } catch (error) { }
    },

    //  学科选择框发生变化后触发的函数
    async onSubjectChange (val) {
      this.form.tags = null
      this.form.catalogID = null
      const { data: res } = await directory({ subjectID: val })
      this.directory = res.items
      console.log('目录', this.directory)
      this.getTagList()
    },
    //  获取标签列表
    async getTagList () {
      const { data: res } = await tags({
        subjectID: this.form.subjectID
      })
      this.tagList = res.items
      console.log('标签列表', this.tagList)
    },
    // 点击链接展示弹出层
    async showPreview (item) {
      // console.log(item)
      // console.log(this.$refs.pr)
      this.showDialog = true
      this.questionDetail = item
      // 执行$nextTick(),DOM更新之后再调用子组件方法=>解决了500的错误
      await this.$nextTick()
      // 调用子组件的获取问题详情的方法
      this.$refs.pr.getQuestionsDetail()
    },
    // 去修改试题的页面
    toEdit (row) {
      this.$router.push({
        path: 'new',
        query: {
          id: row.id
        }
      })
    },
    // 获取题库列表数据
    async getQuestion () {
      const { data } = await getques({ ...this.form, ...this.provAndCity })
      // console.log('题库信息', data)
      this.questions = data.items
      // 获取总条数
      this.total = data.counts
      // console.log('数据总数', this.total)
    },
    // 切换每页数据条数
    changeSize (size) {
      // console.log(size)
      this.form.pagesize = size
      if (this.form.pagesize === size) {
        this.form.page = 1
        this.getQuestion()
      }
    },
    // 分页切换列表数据
    changePage (newPage) {
      this.form.page = newPage
      this.getQuestion()
    },

    // 选择精选
    async choiceAdd (item) {
      const result = await this.$confirm('此操作将该题目加入精选, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).catch(err => err)
      // 如果确认就加入精选 否则什么都不做
      if (result === 'confirm') {
        const data = await choiceAdd({
          id: item.id,
          choiceState: 1
        })
        if (data.status === 200) {
          this.$message.success('加入精选成功')
        }
        // 更新题库列表
        this.getQuestion()
      }
    },
    //  删除题库中的题
    async doDelete (id) {
      try {
        await remove({ id })
        this.$message.success('成功删除了用户!')
        // 纠正页码错误 => 因为：上边已经删除一条数据了，所以需要减一
        const newPage = Math.ceil((this.total - 1) / this.form.pagesize)
        // 页码 > 0 (默认页码最小是1)
        if (newPage > 0) {
          // 纠正页码
          this.form.page = this.form.page > newPage ? newPage : this.form.page
        }
        this.getQuestion()
      } catch (err) {
        this.$message.error('删除失败!')
      }
    },
    // 删除
    Delete (userId) {
      this.$confirm('此操作将永久删除用户 ' + ', 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.doDelete(userId)
        })
        .catch(() => {
          this.$message.info('已取消操作!')
        })
    },
    // 格式化枚举-难度
    formdifficulty (type) {
      // console.log('11:', type)
      // 映射关系
      const maps = {}
      difficulty.forEach(item => {
        maps[item.value] = item.label
      })
      // console.log(maps)
      return maps[type]
    },
    // 格式化枚举-题型
    formquestionType (type) {
      // console.log('11:', type)
      // 映射关系
      const maps = {}
      questionType.forEach(item => {
        maps[item.value] = item.label
      })
      // console.log(maps)
      return maps[type]
    }
  }

}

</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.alert {
  margin: 10px 0px;
}

.top_title {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  span {
    font-size: 12px;
    color: pink;
  }
}
.app-container {
  padding: 10px;
}
.pagination {
  margin-top: 10px;
  text-align: right;
}
</style>

<style>
.el-table th {
  background-color: #fafafa;
}
.el-table th.is-leaf {
  border-bottom: 2px solid #e8e8e8;
}
.disabled td {
  background-color: #f9f9f9;
  color: #c1c1c1;
}
.disabled .el-button--primary,
.disabled .el-button--danger {
  background-color: #dbdada;
  border: 1px solid #dbdada;
  color: #999;
  cursor: not-allowed;
}
.el-pagination__jump {
  margin-left: -1px;
}

.el-table th {
  background-color: #fafafa;
}
.el-table th.is-leaf {
  border-bottom: 2px solid #e8e8e8;
}
.disabled td {
  background-color: #f9f9f9;
  color: #c1c1c1;
}
</style>
